package com.lhh.springcommon.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * 实体类注入配置类
 * @author 李厚航
 */
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时注入
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 为逻辑删除字段填充默认值
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
    }

    /**
     * 修改时注入
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 检查是否是软删除操作
        Object deleted = getFieldValByName("deleted", metaObject);
        if (deleted != null && deleted.equals(1)) {
            // 如果是软删除，设置删除时间
            this.strictUpdateFill(metaObject, "deletedTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

}
